<template>
	<view class="skill-animate-warp" v-if="!destroy">
		<image class="frame" mode="aspectFit" :style="{marginTop:distance + 'px'}" v-for="(frame, index) in frames_images" :key="index" :src="frame" :alt="'frame-' + index"
			v-show="currentFrameIndex === index" />
	</view>
</template>

<script>
	
	const imageCache = {};
	
	export default {
		props: {
			skillid:Number
		},
		data() {
			return {
				currentFrameIndex: 0,
				intervalId: null,
				frames_images : [],
				destroy : false,
				distance : 0,
				frames : 0,
				duration : 0,
				loop : false
			};
		},
		mounted() {

			
			const skill = this.$data_skill.find(item => item.id == this.skillid)
			
			
			this.distance = skill.distance;
			this.frames = skill.frame;
			this.duration = skill.duration;
			this.loop = skill.loop;
			
			this.preloadImages();
			
			if(getApp().globalData.appVisibleState == 'onShow'){
				this.startAnimation();
			}
			
			
		},
		deactivated() {
			clearInterval(this.intervalId);
			this.intervalId = null;
		},
		destroyed() {
			clearInterval(this.intervalId);
			this.intervalId = null;
		},
		methods: {
			preloadImages() {
				
				for (let i = 1; i <= this.frames; i++) {
					//const imagePath = `https://gyw304.gitee.io/legendary-warrior/static/assets/skills/${this.skillid}/${i}.png`;
					const imagePath = `../../static/assets/skills/${this.skillid}/${i}.png`;
	
					// 检查图片是否已在缓存中
					if (!imageCache[imagePath]) {
						const img = new Image();
						img.onload = () => imageCache[imagePath] = img;
						img.src = imagePath;
					}
	
					this.frames_images.push(imagePath);
				}
			},
			startAnimation() {

				const frameInterval = this.duration / this.frames;

				this.intervalId = setInterval(() => {
					this.currentFrameIndex = (this.currentFrameIndex + 1) % this.frames;
					if (!this.loop && this.currentFrameIndex >= this.frames - 1) {
						this.destroy = true
						clearInterval(this.intervalId);
						this.intervalId = null
					}
				}, frameInterval);
			}
		}
	};
</script>

<style lang="scss">
	/* 调整样式 */
	.skill-animate-warp{
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height:100%;
		position: absolute;
		left:0;
		top:0;
		right:0;
		bottom:0;
		z-index: 1;
		.frame{
			position: absolute;
		}
	}
</style>